package dao;

import java.sql.*;

public class BaseDao {
    //4  四个字符串
    final public static String DRIVER = "com.mysql.jdbc.Driver";
    final public static String URL = "jdbc:mysql://localhost:3306/db_ncs?serverTimezone=UTC";
    final public static String UID = "root";
    final public static String PWD = "123456";

    //3  三个对象
    protected Connection conn = null;
    protected PreparedStatement pst = null;
    protected ResultSet rs = null;

    //2
    protected void open_db() {
        try {
            conn= DriverManager.getConnection(URL,UID,PWD);
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }
    protected void close_db() {
        try {
            if (rs!=null) {
                rs.close();
            }
            if (pst!=null) {
                pst.close();
            }
            if (conn!=null) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询方法
     * @param sql
     * @return
     * @throws SQLException
     */
    protected ResultSet getData(String sql) throws SQLException {
        //打开数据库
        open_db();
        pst = conn.prepareStatement(sql);
        //查询
        rs=pst.executeQuery();
        return rs;
    }

    /**
     * 更新方法
     * @param sql
     * @return
     */
    protected int modify(String sql) {
        int result=0;
        try {
            open_db();
            pst=conn.prepareStatement(sql);
            result=pst.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            close_db();
        }
        return result;
    }
    //1
    static {
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}